import { baseUrl, white_list } from './env'
import store from '../../store/index';
import Router from "../../router";
import {loginOutFun} from "../../assets/v1/js/common"

export default (type = 'GET', url = '', data = {}, successCallback = {}, failCallback = {}, method = 'fetch') => {
  type = type.toUpperCase()
  url = baseUrl + url
  let dataStr = '' // 数据拼接字符串
  if (type === 'GET') {

    Object.keys(data).forEach(key => {
      if( data[key]!=null&&data[key]!='null'&&data[key] !== undefined ){
        dataStr += key + '=' + data[key] + '&'
      }
    })
    if (dataStr !== '') {
      dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'))
      url = url + '?' + dataStr
    }
  }
  let requestObj
  if (window.XMLHttpRequest) {
    requestObj = new XMLHttpRequest()
  } else {
    /* eslint-disable */
    requestObj = new ActiveXObject
    /* eslint-enable */
  }
  requestObj.open(type, url, true)
  let sendData = ''
  if (type === 'POST' || type === 'DELETE' || type === 'PUT') {
    sendData = JSON.stringify(data)
  }
  /*let ok = false;
  white_list.forEach(function (item) {
    if (url.indexOf(item) > -1) {
      ok = true;
      return false;
    }
  })*/
  let ok = false
  let path = url.split('?')[0];
  white_list.forEach(function (item) {
    let paths = path.split(item);
    if(paths.length == 2 && paths[1] == '') {
      ok = true
      return false
    }
  })
  if (!ok) {
    requestObj.setRequestHeader('Authorization', 'Bearer ' + JSON.parse(window.sessionStorage.getItem('store') || '{}').token);
    requestObj.setRequestHeader('per', JSON.parse(window.sessionStorage.getItem('store') || '{}').per);
  }
  requestObj.setRequestHeader('uid', JSON.parse(window.sessionStorage.getItem('store') || '{}').userId);
  let tenantId = window.sessionStorage.getItem('tid');
  if (tenantId){
    requestObj.setRequestHeader('tid', tenantId)
  }
  requestObj.setRequestHeader('local-host-ip', window.sessionStorage.getItem('local-host-ip'))
  requestObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
  requestObj.send(sendData)
  requestObj.onreadystatechange = () => {
    if (requestObj.readyState === 4) {
      if (requestObj.status === 200 || requestObj.status === 500) {
        let obj = requestObj.response
        if (obj && typeof obj !== 'object') {
          try {
            obj = JSON.parse(obj)
          } catch (e) {
            alert('网络异常，请稍后再试')
            obj = {}
          }
        }
        if (successCallback && typeof successCallback === 'function') {
          successCallback(obj)
        }
        return obj
      } else if (requestObj.status === 401) {
        let user = getUser();
        if(!user || !user.userId){
          // Router.push({ name: 'login' });
          loginOutFun()
        }else{
          Router.push({ name: '401'});
        }
      }else if(requestObj.status == 403){
        Router.push({ name: 'page_timeout'});
      }else if(response.response && response.response.status == 423){
        let ip=response.response.headers.multiloginip;
        let time=response.response.headers.multilogintime;
        BootstrapDialog.alert("您的账号于"+time+"在"+ip+"设备上登录，如非本人操作，请及时修改密码");
      } else {
        throw new Error(requestObj)
      }
    }
  }
}


